package su.msk.jet.team01.chatik.server.data;

import su.msk.jet.team01.chatik.server.exception.NameInUseException;

import java.util.Formatter;
import java.util.Locale;

public final class Client {

	private Feedback feedback;
	private Room room = DataManager.getDefaultRoom();
	private String name = "";

	public Client(Feedback feedback) {
		this.feedback = feedback;
		
		room.addClient(this);
	}

	public void changeName(final String newName) throws NameInUseException {
		DataManager.changeClientName(this, newName);
	}

	public void changeRoom(final Room newRoom) {
		room.removeClient(this);
		newRoom.addClient(this);
		room = newRoom;
	}

	public void destroy() {
		DataManager.removeClient(this);
		room.removeClient(this);
	}

	public String getName() {
		return name;
	}

	public Room getRoom() {
		return room;
	}

	public void send(final String msg, final Object... args) {
		Formatter formatter = new Formatter();
		formatter.format(Locale.getDefault(), msg, args);
		String result = formatter.out().toString();
		formatter.close();

		feedback.sendMessage(result);
	}

	public void setName(final String newName) {
		name = newName;
	}

	@Override
	public String toString() {
		return name;
	}
	
	public void disconnect() {
		feedback.disconnect();
	}
}
